package com.rg.servlet;

import com.rg.model.GoodsModel;
import com.rg.model.OrderModel;
import com.rg.service.GoodsService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/addGoodsCartServlet")
public class addGoodsCartServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer goodsid=Integer.valueOf(request.getParameter("goodsid"));
        Integer addnum=Integer.valueOf(request.getParameter("addnum"));
        OrderModel order=null;
        HttpSession session=request.getSession();
        if(session.getAttribute("order")!=null){
            order=(OrderModel) session.getAttribute("order");
        }else{
            order=new OrderModel();
            session.setAttribute("order",order);
        }
        GoodsService goodsService=new GoodsService();
        GoodsModel goods=goodsService.selectOneGoodsBygoodsId(goodsid);
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        PrintWriter out =response.getWriter();
        String jsonstr=null;
        if (goods!=null&&goods.getGoodsStock()>=addnum){
            System.out.println("添加");
            order.addGoods(goods,addnum);
            System.out.println("add方法执行过了");
            jsonstr="{\"code\":201,\"msg\":\"success\"}";
            out.println(jsonstr);
        }else {
            jsonstr="{\"code\":401,\"msg\":\"fail\"}";
            out.println(jsonstr);
        }
        out.flush();
        out.close();
    }
}
